package com.ok.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ok.common.domain.po.Result;
import com.ok.common.exception.CustomException;
import com.ok.common.utils.JwtUtils;
import com.ok.gateway.config.AuthProperties;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取Request,Response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 2.判断是否不需要拦截
        if(isExclude(request.getPath().toString())){
            // 无需拦截，直接放行
            return chain.filter(exchange);
        }
        // 3.获取请求头中的token
        String token = null;
        List<String> headers = request.getHeaders().get("Authorization");
        log.info("请求头中的authorization = {}",headers);
        if (!CollUtil.isEmpty(headers)) {
            token = headers.get(0);
            log.info("token = {}",token);
            // 4.校验并解析token
            String adminId = null;
            try {
                Claims claims = JwtUtils.parseJWT(token);
                adminId = String.valueOf(claims.get("adminId")) ;
            } catch (RuntimeException e) {
                // 如果无效，拦截
                String err = "管理员未登录";
                DataBuffer wrap = headOff(exchange,response,err);
                return response.writeWith(Mono.fromSupplier(() -> wrap));
            }

            // TODO 5.如果有效，传递用户信息
            System.out.println("adminId = " + adminId);
            String adminInfo = adminId;
            ServerWebExchange ex = exchange.mutate()    //mutate就是对下游请求做更改
                    .request(b -> b.header("admin-info",adminInfo))
                    .build();
            // 6.放行
            return chain.filter(ex);
        }

        List<String> headers2 = request.getHeaders().get("jwt");
        log.info("请求头中的jwt = {}",headers2);
        if (!CollUtil.isEmpty(headers2)){
            token = headers2.get(0);
            log.info("token ={}",token);
            //检验并解析token
            String userId = null;
            try {
                Claims claims = JwtUtils.parseJWT(token);
                userId = String.valueOf(claims.get("userId")) ;
            } catch (Exception e) {
                String err = "用户未登录";
                DataBuffer wrap = headOff(exchange,response,err);
                return response.writeWith(Mono.fromSupplier(() -> wrap));
            }

            System.out.println("userId="+userId);
            String userInfo = userId;
            ServerWebExchange ex =exchange.mutate()
                    .request(b -> b.header("user-info",userInfo))
                    .build();
            // 6.放行
            return chain.filter(ex);
        }

        String err = "未登录";
        DataBuffer wrap = headOff(exchange,response,err);
        return response.writeWith(Mono.fromSupplier(() -> wrap));
    }

    private boolean isExclude(String antPath) {
        //排除路径
        for (String pathPattern : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(pathPattern, antPath)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }

    /*
          如果无效，拦截
     */
    @SneakyThrows
    public DataBuffer headOff(ServerWebExchange exchange,ServerHttpResponse response,String err){
        response.setStatusCode(HttpStatus.LOCKED);
        DataBufferFactory bufferFactory = response.bufferFactory();
        ObjectMapper objectMapper = new ObjectMapper();
        log.info("ip limit : {}", exchange.getRequest().getPath());
        // 要写入的数据对象，会自动转为json格式
        DataBuffer wrap = bufferFactory.wrap(objectMapper.writeValueAsBytes(Result.error(401,err)));
        log.info("wrap:{}",wrap);
        return wrap;
    }
}